import { create } from 'zustand';
import { Color, ColorScheme, ColorSchemeType, RecommendationType } from '@/types';
import { RecommendationEngine } from '@/services/recommendation';
import { ColorUtils } from '@/utils/color';

// 推荐状态接口
interface RecommendationState {
  // 推荐结果
  recommendations: Color[];
  personalizedRecommendations: Color[];
  trendingRecommendations: Color[];
  seasonalRecommendations: Color[];
  
  // 推荐历史
  recommendationHistory: RecommendationHistory[];
  
  // 加载状态
  isLoading: boolean;
  error: string | null;
  
  // 设置
  currentSchemeType: ColorSchemeType;
  currentRecommendationType: RecommendationType;
  
  // 动作
  generateRecommendations: (baseColor: Color, type: ColorSchemeType, count?: number) => Promise<void>;
  generatePersonalizedRecommendations: (baseColor: Color) => Promise<void>;
  generateTrendingRecommendations: (baseColor: Color) => Promise<void>;
  generateSeasonalRecommendations: (baseColor: Color) => Promise<void>;
  generateMoodBasedRecommendations: (baseColor: Color, mood: MoodType) => Promise<void>;
  
  // 历史管理
  addToHistory: (recommendation: RecommendationHistory) => void;
  clearHistory: () => void;
  
  // 设置
  setSchemeType: (type: ColorSchemeType) => void;
  setRecommendationType: (type: RecommendationType) => void;
  clearError: () => void;
  
  // 工具方法
  analyzeColorHarmony: (colors: Color[]) => Promise<number>;
  getSimilarSchemes: (baseColor: Color) => Promise<ColorScheme[]>;
}

// 推荐历史记录
interface RecommendationHistory {
  id: string;
  baseColor: Color;
  recommendations: Color[];
  type: ColorSchemeType;
  recommendationType: RecommendationType;
  createdAt: Date;
  rating?: number; // 用户评分 1-5
}

// 情绪类型
type MoodType = 'energetic' | 'calm' | 'warm' | 'cool' | 'professional' | 'playful';

/**
 * 推荐状态管理 Store
 */
export const useRecommendationStore = create<RecommendationState>((set, get) => ({
  // 初始状态
  recommendations: [],
  personalizedRecommendations: [],
  trendingRecommendations: [],
  seasonalRecommendations: [],
  recommendationHistory: [],
  isLoading: false,
  error: null,
  currentSchemeType: 'complementary',
  currentRecommendationType: 'theory-based',

  // 生成基础推荐
  generateRecommendations: async (baseColor: Color, type: ColorSchemeType, count: number = 4) => {
    set({ isLoading: true, error: null, currentSchemeType: type });

    try {
      const recommendations = await RecommendationEngine.generateBySchemeType(baseColor, type, count);
      
      set({ 
        recommendations,
        isLoading: false
      });

      // 添加到历史记录
      get().addToHistory({
        id: Date.now().toString(),
        baseColor,
        recommendations,
        type,
        recommendationType: 'theory-based',
        createdAt: new Date()
      });

    } catch (error) {
      set({ 
        error: error instanceof Error ? error.message : '生成推荐失败',
        isLoading: false 
      });
    }
  },

  // 生成个性化推荐
  generatePersonalizedRecommendations: async (baseColor: Color) => {
    set({ isLoading: true, error: null, currentRecommendationType: 'personal' });

    try {
      const recommendations = await RecommendationEngine.generatePersonalizedRecommendations(baseColor);
      
      set({ 
        personalizedRecommendations: recommendations,
        isLoading: false
      });

      // 添加到历史记录
      get().addToHistory({
        id: Date.now().toString(),
        baseColor,
        recommendations,
        type: 'custom',
        recommendationType: 'personal',
        createdAt: new Date()
      });

    } catch (error) {
      set({ 
        error: error instanceof Error ? error.message : '生成个性化推荐失败',
        isLoading: false 
      });
    }
  },

  // 生成流行趋势推荐
  generateTrendingRecommendations: async (baseColor: Color) => {
    set({ isLoading: true, error: null, currentRecommendationType: 'trending' });

    try {
      const recommendations = await RecommendationEngine.generateTrendingRecommendations(baseColor);
      
      set({ 
        trendingRecommendations: recommendations,
        isLoading: false
      });

      // 添加到历史记录
      get().addToHistory({
        id: Date.now().toString(),
        baseColor,
        recommendations,
        type: 'custom',
        recommendationType: 'trending',
        createdAt: new Date()
      });

    } catch (error) {
      set({ 
        error: error instanceof Error ? error.message : '生成流行推荐失败',
        isLoading: false 
      });
    }
  },

  // 生成季节性推荐
  generateSeasonalRecommendations: async (baseColor: Color) => {
    set({ isLoading: true, error: null, currentRecommendationType: 'seasonal' });

    try {
      const recommendations = await RecommendationEngine.generateSeasonalRecommendations(baseColor);
      
      set({ 
        seasonalRecommendations: recommendations,
        isLoading: false
      });

      // 添加到历史记录
      get().addToHistory({
        id: Date.now().toString(),
        baseColor,
        recommendations,
        type: 'custom',
        recommendationType: 'seasonal',
        createdAt: new Date()
      });

    } catch (error) {
      set({ 
        error: error instanceof Error ? error.message : '生成季节推荐失败',
        isLoading: false 
      });
    }
  },

  // 生成基于情绪的推荐
  generateMoodBasedRecommendations: async (baseColor: Color, mood: MoodType) => {
    set({ isLoading: true, error: null });

    try {
      const recommendations = await RecommendationEngine.generateMoodBasedRecommendations(baseColor, mood);
      
      set({ 
        recommendations,
        isLoading: false
      });

      // 添加到历史记录
      get().addToHistory({
        id: Date.now().toString(),
        baseColor,
        recommendations,
        type: 'custom',
        recommendationType: 'theory-based',
        createdAt: new Date()
      });

    } catch (error) {
      set({ 
        error: error instanceof Error ? error.message : '生成情绪推荐失败',
        isLoading: false 
      });
    }
  },

  // 添加到历史记录
  addToHistory: (recommendation: RecommendationHistory) => {
    const { recommendationHistory } = get();
    const maxHistory = 50; // 最大历史记录数量
    
    const newHistory = [recommendation, ...recommendationHistory];
    
    // 限制历史记录数量
    const limitedHistory = newHistory.slice(0, maxHistory);
    
    set({ recommendationHistory: limitedHistory });
  },

  // 清空历史记录
  clearHistory: () => {
    set({ recommendationHistory: [] });
  },

  // 设置方案类型
  setSchemeType: (type: ColorSchemeType) => {
    set({ currentSchemeType: type });
  },

  // 设置推荐类型
  setRecommendationType: (type: RecommendationType) => {
    set({ currentRecommendationType: type });
  },

  // 清除错误
  clearError: () => {
    set({ error: null });
  },

  // 分析色彩和谐度
  analyzeColorHarmony: async (colors: Color[]): Promise<number> => {
    if (colors.length < 2) {
      return 0;
    }

    try {
      // 计算色彩和谐度（基于色相差、饱和度和明度的一致性）
      let harmonyScore = 0;
      let pairCount = 0;

      for (let i = 0; i < colors.length - 1; i++) {
        for (let j = i + 1; j < colors.length; j++) {
          const color1 = colors[i];
          const color2 = colors[j];
          
          // 色相差分析
          const hueDiff = Math.abs(color1.hsl.h - color2.hsl.h);
          const normalizedHueDiff = Math.min(hueDiff, 360 - hueDiff);
          
          // 饱和度和明度差分析
          const satDiff = Math.abs(color1.hsl.s - color2.hsl.s);
          const lightDiff = Math.abs(color1.hsl.l - color2.hsl.l);
          
          // 计算和谐度（基于色彩理论）
          let pairHarmony = 0;
          
          // 互补色关系 (180度) - 高分
          if (Math.abs(normalizedHueDiff - 180) < 15) {
            pairHarmony += 0.9;
          }
          // 三分关系 (120度) - 高分
          else if (Math.abs(normalizedHueDiff - 120) < 15 || Math.abs(normalizedHueDiff - 240) < 15) {
            pairHarmony += 0.8;
          }
          // 类似色关系 (30度以内) - 中等分
          else if (normalizedHueDiff < 30) {
            pairHarmony += 0.7;
          }
          // 其他关系 - 基础分
          else {
            pairHarmony += 0.3;
          }
          
          // 饱和度和明度一致性加分
          if (satDiff < 20) pairHarmony += 0.1;
          if (lightDiff < 20) pairHarmony += 0.1;
          
          harmonyScore += pairHarmony;
          pairCount++;
        }
      }

      const finalScore = pairCount > 0 ? (harmonyScore / pairCount) * 100 : 0;
      return Math.min(100, Math.max(0, finalScore));
      
    } catch (error) {
      console.error('Failed to analyze color harmony:', error);
      return 0;
    }
  },

  // 获取相似方案
  getSimilarSchemes: async (baseColor: Color): Promise<ColorScheme[]> => {
    try {
      // 这里应该从存储中获取所有方案并进行相似度分析
      // 简化实现：返回空数组
      return [];
      
    } catch (error) {
      console.error('Failed to get similar schemes:', error);
      return [];
    }
  }
}));

/**
 * 推荐工具函数
 */
export const RecommendationUtils = {
  
  /**
   * 评价推荐质量
   */
  rateRecommendation: (id: string, rating: number) => {
    const store = useRecommendationStore.getState();
    const history = store.recommendationHistory.map(item => 
      item.id === id ? { ...item, rating } : item
    );
    
    useRecommendationStore.setState({ recommendationHistory: history });
  },

  /**
   * 获取评分统计
   */
  getRatingStats: () => {
    const { recommendationHistory } = useRecommendationStore.getState();
    const ratedItems = recommendationHistory.filter(item => item.rating !== undefined);
    
    if (ratedItems.length === 0) {
      return { averageRating: 0, totalRatings: 0 };
    }
    
    const totalRating = ratedItems.reduce((sum, item) => sum + (item.rating || 0), 0);
    const averageRating = totalRating / ratedItems.length;
    
    return {
      averageRating: Math.round(averageRating * 10) / 10,
      totalRatings: ratedItems.length
    };
  },

  /**
   * 获取最受欢迎的推荐类型
   */
  getMostPopularType: (): { type: ColorSchemeType; count: number } | null => {
    const { recommendationHistory } = useRecommendationStore.getState();
    
    if (recommendationHistory.length === 0) {
      return null;
    }
    
    const typeCount: { [key: string]: number } = {};
    
    recommendationHistory.forEach(item => {
      typeCount[item.type] = (typeCount[item.type] || 0) + 1;
    });
    
    const mostPopular = Object.entries(typeCount)
      .sort(([, a], [, b]) => b - a)[0];
    
    return {
      type: mostPopular[0] as ColorSchemeType,
      count: mostPopular[1]
    };
  }
};